package com.generalbackend.handler;

import com.alibaba.fastjson.JSONObject;
import com.generalbackend.common.constants.Constants;
import com.generalbackend.common.model.CommonResult;
import com.generalbackend.common.model.entity.User;
import com.generalbackend.common.util.ClientUtil;
import com.generalbackend.common.util.SnowFlakeIdGeneratorUtil;
import com.generalbackend.role.model.entity.UserLoginHistory;
import com.generalbackend.role.service.IUserLoginHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author tim.xie
 * @date 2021/12/28 16:42
 */
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Resource
    private MappingJackson2HttpMessageConverter messageConverter;
    @Autowired
    private IUserLoginHistoryService userLoginHistoryService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        JSONObject json = (JSONObject) request.getAttribute("loginMessage");
        if (json != null) {
            User user = (User)json.get(Constants.USER_INFO);
            if(user != null && user.getId() != null){
                UserLoginHistory userLoginHistory = new UserLoginHistory();
                userLoginHistory.setId(SnowFlakeIdGeneratorUtil.nextId());
                userLoginHistory.setLoginIp(ClientUtil.getIpAddr(request));
                userLoginHistory.setIsSuccess(0);
                userLoginHistory.setUserId(user.getId());
                userLoginHistoryService.insert(userLoginHistory);
            }
        }
        CommonResult res = CommonResult.errorCommonResult("登录失败,输入的帐号或者密码错误!");
        messageConverter.write(res, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
    }
}
